package com.chatgpt.api.controller;


import com.chatgpt.api.service.entity.User;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * 控制器基类
 *
 * @author yangjian
 */
public abstract class BaseController {
    public static String LOGIN_USER = "ChatPlus_Login_User";

    protected Integer getIntParam(HttpServletRequest request, String name) {
        String value = request.getParameter(name);
        if (StringUtils.isEmpty(value)) {
            return 0;
        }
        int result;
        try {
            result = Integer.parseInt(value);
        } catch (Exception e) {
            return 0;
        }
        return result;
    }

    /**
     * 获取字符串参数，默认会去掉字符串两边的空格，如果全是空格，则返回 null
     *
     * @param request http 请求对象
     * @param name    参数名称
     * @return 返回处理后的参数值
     */
    protected String getStrParam(HttpServletRequest request, String name) {
        return StringUtils.trimToNull(request.getParameter(name));
    }

    protected boolean getBooleanParam(HttpServletRequest request, String name) {
        return Boolean.parseBoolean(request.getParameter(name));
    }

    protected Long getLongParam(HttpServletRequest request, String name) {
        return Long.valueOf(request.getParameter(name));
    }

    protected BigInteger getBigIntegerParam(HttpServletRequest request, String name) {
        return new BigInteger(getStrParam(request, name));
    }

    protected BigDecimal getBigDecimalParam(HttpServletRequest request, String name) {
        return new BigDecimal(getStrParam(request, name));
    }


    protected User getLoginUser(HttpServletRequest request) {
        return (User) request.getAttribute(LOGIN_USER);
    }

    protected Integer getLoginUserId(HttpServletRequest request) {
        return ((User) request.getAttribute(LOGIN_USER)).getId();
    }
}


